package com.yueyin.ui.main;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.yueyin.MainActivity;
import com.yueyin.R;
import com.yueyin.databinding.ActivityDirsBinding;

import java.io.File;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MusicScan extends AppCompatActivity {


    ActivityDirsBinding binding;

    private ListView lvDirList;


    private String rootDir = "/storage";//设置根目录
    private File root;//
    private final Map<String, List<Data>> dirs = new HashMap<>();//存储文件夹名
    private final List<Data> fileMusicData = new ArrayList<>();
    private final List<Data> fileLrcData = new ArrayList<>();

    private final List<File> listDir = new ArrayList<>();
    private static final int REQUEST_EXTERNAL_STORAGE = 1;

    private final String[] PERMISSIONS_STORAGE = {
            "android.permission.READ_EXTERNAL_STORAGE"
    };


    public void verifyStoragePermissions(Activity activity) {
        try {
            int permission = ActivityCompat.checkSelfPermission(activity, PERMISSIONS_STORAGE[0]);

            if (permission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dirs);

        verifyStoragePermissions(this);

        File externalStorage = Environment.getExternalStorageDirectory();

        binding = ActivityDirsBinding.inflate(getLayoutInflater());
        lvDirList = findViewById(R.id.lvDirList);

        if (externalStorage != null) {
            root = externalStorage;
            rootDir = root.getAbsolutePath();
        } else {
            root = new File(rootDir);
        }


        collectDirs();
        //addListView();
        if (!dirs.isEmpty()) {
            MyAdapter adapter = new MyAdapter(getApplicationContext(), dirs.get(rootDir), binding);
            lvDirList.setAdapter(adapter);
            lvDirList.setOnItemClickListener(new ListItemClick());
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.music_scan, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.startScan) {
            scanMusic();
            Intent intent = new Intent(this, MainActivity.class);
            finish();
            startActivity(intent);
            //开始扫描
        }
        return super.onOptionsItemSelected(item);
    }


    //添加listview点击功能  选择某个目录  进入下一级
    public class ListItemClick implements OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long p2) {
            //获取点击的目录名
            CharSequence selectedDir = ((TextView) view.findViewById(R.id.tvDir)).getText();
            root = new File(rootDir + File.separator + selectedDir);
            rootDir += (File.separator + selectedDir);//保存当前目录  返回上层时使用
            //dirs.clear();
            collectDirs();

            if (dirs.get(rootDir) != null) {
                MyAdapter adapter = new MyAdapter(getApplicationContext(), dirs.get(rootDir), binding);
                lvDirList.setAdapter(adapter);
            }
        }

    }

    //返回上层目录
    public void back() {
        rootDir = rootDir.substring(0, rootDir.lastIndexOf("/"));
        root = new File(rootDir);
        dirs.clear();
        collectDirs();
        MyAdapter adapter = new MyAdapter(getApplication(), dirs.get(rootDir), binding);
        lvDirList.setAdapter(adapter);
    }

    //按手机返回键退回到主Activity
    public boolean onKeyDown(int keyCode, KeyEvent e) {
        if (keyCode == KeyEvent.KEYCODE_BACK && !rootDir.equals("/storage")) {
            back();
            return false;
        } else if (keyCode == KeyEvent.KEYCODE_BACK) {
            this.finish();
            Intent intent = new Intent(this, MainActivity.class);
            startActivity(intent);

            return true;
        }
        return super.onKeyDown(keyCode, e);
    }


    //将下一级目录 存到list中 之后显示到ListView 以供浏览
    public void collectDirs() {
        List<Data> temp = new ArrayList<>();
        File[] files = root.listFiles();

        if (files != null) {
            for (File file : files) {
                //收集目录，排除隐藏目录
                if (file.isDirectory() && !file.getName().startsWith(".")) {
                    Data data = new Data();
                    data.setPath(file.getName());
                    temp.add(data);
                }
            }

            //排序
            temp.sort(Comparator.comparing(Data::getPath));
            dirs.put(root.getAbsolutePath(), temp);
        }

    }

    //收集子目录
    public void getDirs(File file) {

        if (file.isDirectory()) {
            //
            File[] dirs = file.listFiles(File::isDirectory);

            if (dirs != null) {

                for (File dir : dirs) {
                    if (!dir.getName().startsWith(".")) {
                        listDir.add(dir);
                        getDirs(dir);
                    }
                }
            }
        }
    }

    public void scanFile(boolean isLrc) {
        listDir.clear();
        listDir.add(root);//添加当前目录
        getDirs(root);//添加子目录

        if (isLrc) {
            listDir.forEach(dir -> {
                File[] files = dir.listFiles();

                if (files != null) {
                    for (File file : files) {
                        String fullName = file.getAbsolutePath();//.toLowerCase(locale);

                        if (fullName.endsWith("mp3") || fullName.endsWith("ape") || fullName.endsWith("flac")) {
                            String fileName = fullName.substring(fullName.lastIndexOf("/") + 1, fullName.lastIndexOf(".")).trim();

                            Data data = new Data();
                            data.setPath(fullName);
                            data.setSize(file.length());

                            if (fileName.contains(" - ")) {
                                String[] coupleData = fileName.split(" - ");
                                data.setName(coupleData[0]);
                                data.setAuthor(coupleData[1]);
                            } else {
                                data.setName(fileName);
                            }

                            fileMusicData.add(data);
                        }
                    }
                }
            });
        } else {
            listDir.forEach(dir -> {
                File[] files = dir.listFiles();

                if (files != null) {
                    for (File file : files) {
                        String fullLrcName = file.getAbsolutePath();

                        if (fullLrcName.endsWith("lrc")) {
                            String fileName = fullLrcName.substring(fullLrcName.lastIndexOf("/") + 1, fullLrcName.lastIndexOf(".")).trim();

                            Data data = new Data();
                            data.setPath(fullLrcName);

                            if (fileName.contains(" - ")) {
                                String[] coupleData = fileName.split(" - ");
                                data.setName(coupleData[0]);
                            } else {
                                data.setName(fileName);
                            }

                            fileLrcData.add(data);
                        }
                    }
                }
            });
        }
    }

    public void scanMusic() {
        SQLiteHelper helper = new SQLiteHelper(getApplicationContext());
        fileMusicData.clear();
        fileLrcData.clear();
        //扫描歌曲
        scanFile(true);
        //扫描歌词
        scanFile(false);
        //写数据库
        for (Data data : fileMusicData) {
            helper.add_File(data, false);
        }

        //写数据库
        for (Data data : fileLrcData) {
            helper.add_File(data, true);
        }

        helper.close();

        Toast.makeText(getApplication(), "扫描完成 !", Toast.LENGTH_SHORT).show();
    }
}
